/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.network;

import java.io.*;
import java.net.*;
import com.cse.p2p.common.*;
import com.cse.p2p.database.*;
import com.cse.p2p.hash.*;
import com.cse.p2p.localfile.*;
import com.cse.p2p.parser.*;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import server.dicfile.DicFileGenerating;
import server.meta.UploadMeta;

/**
 *
 * @author TuyetNgan
 */
public class ServerReceiveDataTask extends Thread {

	private ConcurrentHashMap<String, UploadMeta> uploadMeta;
	private InputStream is = null;
	private Socket socket = null;
//        private int pieceID;
//        private int fileID;
//        private String pieceHash;
//        private String filePath;
	private byte[] content;
	private String IPsender;

	public ServerReceiveDataTask( Socket s, ConcurrentHashMap<String, UploadMeta> list ) {
		this.socket = s;
		this.uploadMeta = list;
//            this.pieceID = id;
//            this.fileID = fid;
//            this.pieceHash = hash;
//            this.filePath = path;
	}

	public void newConnection() {

		try {
			is = socket.getInputStream();
		}
		catch ( IOException e ) {
		}
	}

	public void closeConnection() {
		try {
			socket.close();
		}
		catch ( IOException e ) {
		}
	}

	public byte[] getContent() {
		return content;
	}

	public String getIP() {
		return IPsender;
	}

	@Override
	public void run() {
		newConnection();
		System.out.println( "NETWORK: DATA: Server connected from " + socket.getRemoteSocketAddress().toString() );
		String remote = socket.getRemoteSocketAddress().toString();
		String remoteIP = remote.substring( 1, remote.lastIndexOf( ":" ) );
		UploadMeta metaItem = uploadMeta.get( remoteIP );
		if ( metaItem != null ) {
			try {
				System.out.println( "NETWORK: DATA: Receiving data from " + socket.getRemoteSocketAddress().toString() );
				BufferedOutputStream newFileBOS = new BufferedOutputStream( new FileOutputStream( new File( metaItem.getLocalFilePath() ) ) );
				byte[] buffer = new byte[ CommonSettings.DEFAULT_PACKAGE_SIZE ];
				int readResult = 0;
				while ( ( readResult = is.read( buffer ) ) > 0 ) {
					newFileBOS.write( buffer, 0, readResult );
				}
				newFileBOS.close();
				System.out.println( "NETWORK: DATA: Data recieved from " + socket.getRemoteSocketAddress().toString() );
				String tracker_url = socket.getLocalSocketAddress().toString();
				tracker_url = tracker_url.substring( 1, tracker_url.lastIndexOf( ":" ) );
				System.out.println( tracker_url );
//				ServerDatabase.openDatabase();
				int fileID = ServerDatabase.createNewFileAndReturnFileID( metaItem.getMetadata().getFileName(),metaItem.getLocalFilePath(),
																		  ( new File( metaItem.getLocalFilePath() ).length() ), metaItem.getLocalFilePath(), metaItem.getMetadata().getFileDesc(), remoteIP );
//				ServerDatabase.closeDatabase();
//				int fileID = 10;
				System.out.println( "DATABASE: Save to DB request from " + socket.getRemoteSocketAddress().toString() );

				DicFile dicFile = DicFileGenerating.run( new File( metaItem.getLocalFilePath() ), fileID, metaItem.getMetadata().getFileName(), metaItem.getMetadata().getFileDesc(), remoteIP, tracker_url );
				metaItem.getListenThread().sendDicFile( dicFile );
				uploadMeta.remove( remoteIP, metaItem);
			}
			catch ( Exception e ) {
				System.err.println( e.getMessage() );
				e.printStackTrace();
			}
		}
		closeConnection();
	}
}
